<template>
  <el-upload
    :action="baseUrl + '/credit/peasants/upload/idCardOther'"
    ref="uploadRef"
    v-model:file-list="fileList"
    :headers="hander"
    :multiple="true"
    list-type="picture-card"
    :show-file-list="true"
    :auto-upload="true"
    :on-success="handleOnSuccess"
    :on-remove="handleOnRemove"
    :on-error="handleOnError"
    :on-preview="handlePictureCardPreview"
    :before-remove="handleBeforeRemove"
    :on-exceed="handleOnExceed"
    :limit="maxLimit"
  >
    <el-icon>
      <Plus />
    </el-icon>
  </el-upload>

  <el-dialog v-model="dialogVisible" width="80%" top="80px">
    <img w-full :src="dialogImageUrl" alt="预览图片" style="width: 100%" />
  </el-dialog>
</template>

<script lang="ts" setup>
  import { onMounted, onUpdated, ref, watch } from 'vue'
  import { Plus } from '@element-plus/icons-vue'

  import type { UploadFile, UploadFiles, UploadProps, UploadUserFile } from 'element-plus'
  import { ElMessage } from 'element-plus'
  import { useUserStore } from '@/store/modules/user'
  import { reqUpload } from '@/api/credit/peasants/pea-message/type'

  let $emit = defineEmits(['update:modelValue'])
  let props = defineProps({
    modelValue: {
      required: true,
      default: [],
      type: Array,
    },
    // 上传文件的最大值
    maxLimit: {
      required: true,
    },
    id: {
      required: true,
    },
  })

  const fileList = ref<UploadUserFile[]>([])
  const UserStore = useUserStore()
  const dialogImageUrl = ref('')
  const dialogVisible = ref(false)
  const disabled = ref(false)
  const uploadRef = ref()

  const baseUrl = import.meta.env.VITE_SERVE /*获取请求的ip地址*/

  const hander = ref({
    Authorization: UserStore.token,
  })

  // 删除图片前的调用
  const handleBeforeRemove = (file, fileList) => {
    return new Promise((resolve, reject) => {
      // 这里可以自定义你的移除逻辑，比如发送请求到服务器进行删除操作等
      if (file != null) {
        const index = fileList.findIndex((f) => {
          console.log(f)
          return f.uid === file.uid
        })
        if (index !== -1) {
          // 删除
          props.modelValue.splice(index, 1)
          resolve() // 继续执行默认的移除行为
        }
      }
      // 阻止默认的移除行为
      reject()
    })
  }

  // 超过上传上限的回调函数
  const handleOnExceed = (files: File[], uploadFiles: UploadUserFile[]) => {
    ElMessage.info('只允许上传' + props.maxLimit + '张照片！')
  }

  const handleOnRemove = (uploadFile: UploadFile) => {
    // 将uploadFile在文件列表中进行移除
    // 循环根据uid获奖上传的图片列表进行移除
    console.log('删除方法的调用，删除服务器中的文件')
    ElMessage.success('文件删除成功！')
  }

  const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
    dialogImageUrl.value = uploadFile.url!
    dialogVisible.value = true
  }

  // 上传成功的回调函数
  const handleOnSuccess = (
    response: reqUpload,
    uploadFile: UploadFile,
    uploadFiles: UploadFiles,
  ) => {
    if (response.code == 200) {
      ElMessage.success('上传成功！')
      console.log(response)
      // 将srcList的值进行转换放到props中
      props.modelValue.push(response.fileName)
    } else {
      ElMessage.error('上传失败！请检查连接后重试！')
    }
  }

  // 上传失败的回调函数
  const handleOnError = (error: Error, uploadFile: UploadFile, uploadFiles: UploadFiles) => {
    ElMessage.error('上传失败！' + error)
  }

  watch(
    () => {
      return props.modelValue
    },
    () => {
      if (props.modelValue.length === 0) {
        // 先清除
        uploadRef.value.clearFiles()
        fileList.value = []
      } else if (props.modelValue.length > 0 && props.id != '') {
        // 将props中的照片信息进行封装
        props.modelValue.forEach((item) => {
          // 将里面的元素进行封装
          console.log(item)
          fileList.value.push({
            url: baseUrl + item,
          })
        })
      }
    },
  )

  // 初始化
  onMounted(() => {
    // 将props中的照片信息进行封装
    props.modelValue.forEach((item) => {
      // 将里面的元素进行封装
      console.log(item)
      fileList.value.push({
        url: baseUrl + item,
      })
    })
  })
</script>

<style lang="scss" scoped></style>
